package pe.com.cotelasa.seguridad.dominio.servicio;

import java.util.Properties;

import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.PasswordAuthentication;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;

import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Service;

import pe.com.cotelasa.scp.dominio.excepcion.ServiceException;

@Service("serviceEnviarCorreo")
public class ServicioEnviarCorreoImpl implements IServicioEnviarCorreo {

	private static Logger logger = Logger.getLogger(ServicioEnviarCorreoImpl.class);
 
	@Autowired
    @Qualifier("serviceProperties")
    protected Properties serviceProperties;
	
	@Override
	public void enviarCorreoCambioContracena(String email)
			throws ServiceException {
		 Session session = loguearCorreo(serviceProperties);
		 try {
			 
				Message message = new MimeMessage(session);
				message.setFrom(new InternetAddress(serviceProperties.getProperty("mail.user")));
				message.setRecipients(Message.RecipientType.TO,
					InternetAddress.parse(email));
				message.setSubject("Confirmación del cambio de contraseña [Sistema SCP]");
				message.setText("Su contraseña ha sido cambiado satisfactoriamente,"
					+ "\n\n No spam to my email, please!");
	 
				Transport.send(message);
				logger.info("Correo Enviado a:  " + email);
			} catch (MessagingException e) {
				throw new ServiceException(new RuntimeException(e));
			}
	}
        
        @Override
	public void enviarCorreoUsuario(String email, String nuevaContracenia,String usuario)
			throws ServiceException {
		 Session session = loguearCorreo(serviceProperties);
		 try {
			 
				Message message = new MimeMessage(session);
				message.setFrom(new InternetAddress(serviceProperties.getProperty("mail.user")));
				message.setRecipients(Message.RecipientType.TO,
					InternetAddress.parse(email));
				message.setSubject("Confirmacion de registro");
				message.setText("Su usuario es: "+usuario
                                        + "\n Su Contraseña es: "+nuevaContracenia
					+ "\n\n No spam to my email, please!");
	 
				Transport.send(message);
				logger.info("Correo Enviado a:  " + email);
			} catch (MessagingException e) {
				throw new ServiceException(new RuntimeException(e));
			}
	}
	 
	
	@Override
	public void enviarCorreoError(String mensajeError, Throwable e)
			throws ServiceException {
		 Session session = loguearCorreo(serviceProperties);
		 try {
			 
				Message message = new MimeMessage(session);
				message.setFrom(new InternetAddress(serviceProperties.getProperty("mail.user")));
				message.setRecipients(Message.RecipientType.TO,
					InternetAddress.parse(serviceProperties.getProperty("mail.user")));
				message.setSubject("Error Cotelasa [SCP]");
				message.setText("Ha Ocurrido un Error en el Sistema :\n" +
						        "Mensaje: " + e.getMessage() + " \n" +
						        "\n\n" +
						        "Error:" + e);
	 
				Transport.send(message);
				logger.info("Correo Enviado a: "+ serviceProperties.getProperty("mail.user"));
			} catch (MessagingException ex) {
				logger.error(e.getMessage(),e);
			}
	}
	
	
	private static Session loguearCorreo(Properties properties){
		final String username = properties.getProperty("mail.user");
		final String password = properties.getProperty("mail.pasword");
 
		Properties props = new Properties();
		props.put("mail.smtp.auth", "true");
		props.put("mail.smtp.starttls.enable", "true");
		props.put("mail.smtp.host", properties.getProperty("mail.server"));
		props.put("mail.smtp.port", properties.getProperty("mail.port"));
 
		Session session = Session.getInstance(props,
		  new javax.mail.Authenticator() {
			protected PasswordAuthentication getPasswordAuthentication() {
				return new PasswordAuthentication(username, password);
			}
		  });
		return session;
	}
}
